﻿using Common.Device.DeviceDb;
using Common.Device.Models;
using Common.Device.ViewModels;
using Common.Tool.FileTools;
using Common.View.Controls.Dialogs;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace Common.Device.Views
{
    /// <summary>
    /// TestEditView.xaml 的交互逻辑
    /// </summary>
    public partial class TestEditView : UserControl
    {
        public ViewModels.TestEditViewModel viewModel = new TestEditViewModel(); 
        public TestEditView()
        {
            InitializeComponent();
            DataContext = viewModel;
            viewModel.document = richTextBox.RichDocument;
            //初始空白编辑表
            InsStation(null, null);
        }

        private void InsStation(object sender, RoutedEventArgs e)
        {
            var index = StationTab.Items.Count + 1;
            var tab= new TabControl();
            tab.TabStripPlacement = Dock.Bottom;
            var item = new TabItem();
            item.Header = index.ToString().PadLeft(3, '0');
            item.Content = tab;
            var newitem = new TabItem();
            newitem.Header = "001";
            var view = new Views.TestListView();
            view.viewModel.num = "001";
            view.viewModel.document = viewModel.document;
            newitem.Content = view;
            tab.Items.Add(newitem);
            StationTab.Items.Add(item);
        }

        private void DelStation(object sender, RoutedEventArgs e)
        {
            if (StationTab.Items.Count > 1)
            {
                //删除工装
                StationTab.Items.Remove(StationTab.SelectedItem);
                for (int i = 0; i < StationTab.Items.Count; i++)
                {
                    (StationTab.Items[i] as TabItem).Header = (i + 1).ToString().PadLeft(3, '0');
                }
            }
        }
        /// <summary>
        /// 添加测试通道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InsChannel(object sender, RoutedEventArgs e)
        {
            var item = StationTab.SelectedItem as TabItem;
            var tab = item.Content as TabControl;
            var index = tab.Items.Count + 1;
            var newitem = new TabItem();
            newitem.Header = index.ToString().PadLeft(3, '0');
            var view = new Views.TestListView();
            view.viewModel.num = index.ToString().PadLeft(3, '0');
            view.viewModel.document = viewModel.document;
            newitem.Content = view;
            tab.Items.Add(newitem);
        }

        private void DelChannel(object sender, RoutedEventArgs e)
        {
            var item = StationTab.SelectedItem as TabItem;
            var tab = item.Content as TabControl;
            if (tab.Items.Count > 1)
            {
                tab.Items.Remove(tab.SelectedItem);
                for (int i = 0; i < tab.Items.Count; i++)
                {
                    (tab.Items[i] as TabItem).Header = (i + 1).ToString().PadLeft(3, '0');
                }
            }
        }
        /// <summary>
        /// 加载测试表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Open(object sender, RoutedEventArgs e)
        {
            try
            {

                Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                ofd.RestoreDirectory = true;
                ofd.Title = "选择测试文件";
                ofd.Filter = "ZIP文件|*.zip;";
                if (ofd.ShowDialog() == false)
                {
                    return;
                }
                List<TabItem> tabs = new List<TabItem>();
                //选择路径
                string selectFile = ofd.FileName;
                //目录下文件名
                var files = new ZipHelper().Decompress(selectFile);
                //读取测试文件名
                TextBoxPath.Text = selectFile.Substring(selectFile.LastIndexOf('\\') + 1).Replace(".zip", "");
                //遍历目录下所有文件
                int no = 0;
                foreach (var item in files)
                {
                    //文件名
                    string fileName = item.Key;
                    //测试表格
                    if (fileName.Contains(".xlsx") && fileName.Length == 8)
                    {
                        no++;
                        var tab = new TabControl();
                        tab.TabStripPlacement = Dock.Bottom;
                        var index = no;
                        var tabItem = new TabItem();
                        tabItem.Header = index.ToString().PadLeft(3, '0');
                        tabItem.Content = tab;
                        //读取表格
                        IWorkbook workbook = NpoiHelper.GetWorkbook(item.Key, item.Value);
                        //通道数=sheet
                        int channels = workbook.NumberOfSheets;
                        //遍历通道
                        for (int i = 0; i < channels; i++)
                        {
                            ISheet sheet = workbook.GetSheetAt(i);
                            ObservableCollection<TestOrder> orders = new ObservableCollection<TestOrder>();
                            //遍历表格
                            for (int row = 1; row < sheet.LastRowNum + 1; row++)
                            {
                                //读取每一行测试项
                                TestOrder order = new TestOrder();
                                order.index = Convert.ToInt32(NpoiHelper.ReadCell(sheet, row, 0));
                                order.name = NpoiHelper.ReadCell(sheet, row, 1);
                                var deviceNames = NpoiHelper.ReadCell(sheet, row, 2).Split(new char[] { '\r', '\n' });
                                var orderTemps = NpoiHelper.ReadCell(sheet, row, 3).Split(new char[] { '\r', '\n' });
                                var orderParameters = NpoiHelper.ReadCell(sheet, row, 4).Split(new char[] { '\r', '\n' });
                                var orderMeses = NpoiHelper.ReadCell(sheet, row, 5).Split(new char[] { '\r', '\n' });
                                var orderRanges = NpoiHelper.ReadCell(sheet, row, 8).Split(new char[] { '\r', '\n' });
                                for (int j = 0; j < deviceNames.Length; j++)
                                {
                                    if (deviceNames[j] != "null" && DeviceService.useDevices.ContainsKey(deviceNames[j]) == false)
                                    {
                                        Common.View.Controls.Dialogs.TipView.Show("未识别到设备" + deviceNames[j]);
                                    }
                                    order.orders.Add(new DeviceOrder()
                                    {
                                        Device = (deviceNames[j] == "null" || !DeviceService.useDevices.ContainsKey(deviceNames[j])) ? null : DeviceService.useDevices[deviceNames[j]],
                                        index = j + 1,
                                        no = Encoding.ASCII.GetString(new[] { (byte)(Encoding.ASCII.GetBytes("a")[0] + j) }),
                                        mes = orderMeses.Length > j ? orderMeses[j] : "",
                                        Order = new Order() { name = deviceNames[j], temp = orderTemps[j], deviceModel = orderParameters[j], range = orderRanges[j] }
                                    });
                                }
                                order.testTimes = Convert.ToInt32(NpoiHelper.ReadCell(sheet, row, 6));
                                order.ngStop = NpoiHelper.ReadCell(sheet, row, 7) == "true";
                                orders.Add(order);
                            }
                            //根据测试表新增测试通道
                            var newitem = new TabItem();
                            newitem.Header = (i + 1).ToString().PadLeft(3, '0');
                            var view = new Views.TestListView();
                            view.viewModel.num = index.ToString().PadLeft(3, '0') + "-" + (i + 1).ToString().PadLeft(3, '0');
                            view.viewModel.Orders = orders;
                            view.viewModel.document = viewModel.document;
                            newitem.Content = view;
                            tab.Items.Add(newitem);
                        }
                        //根据测试表新增测试工装
                        tabs.Add(tabItem);
                    }
                }
                if (tabs.Count > 0)
                {
                    //加载table
                    StationTab.Items.Clear();
                    foreach (var item in tabs)
                    {
                        StationTab.Items.Add(item);
                    }
                    StationTab.SelectedIndex = 0;
                    HandyControl.Controls.Growl.Success("加载成功!");
                }
                else
                {
                    HandyControl.Controls.Growl.Warning("加载失败!");
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.Growl.Error("加载失败!"+ex.Message);
            }
        }
        /// <summary>
        /// 保存测试表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
            sfd.Filter = ".zip文件(*.zip)|*.zip";
            sfd.FileName = TextBoxPath.Text.Trim();
            sfd.OverwritePrompt = true;
            if (sfd.ShowDialog() == false)
            {
                return;
            }
            string path = sfd.FileName;
            TextBoxPath.Text = path.Substring(path.LastIndexOf('\\') + 1).Replace(".zip", "");
            Dictionary<string, byte[]> workbooks = new Dictionary<string, byte[]>();
            //循环table control 生成测试工装
            foreach (var item in StationTab.Items)
            {
                var tabItem = item as TabItem;
                var tab = tabItem.Content as TabControl;
                IWorkbook workbook = new XSSFWorkbook();
                ICellStyle cellStyle = workbook.CreateCellStyle();
                cellStyle.WrapText = true;
                cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                foreach (var item2 in tab.Items)
                {
                    //循环table item 生成测试通道
                    var tabItem2 = item2 as TabItem;
                    ISheet sheet = workbook.CreateSheet(tabItem2.Header.ToString());
                    IRow row = sheet.CreateRow(0);
                    row.CreateCell(0).SetCellValue("序号");
                    row.CreateCell(1).SetCellValue("测试项");
                    row.CreateCell(2).SetCellValue("设备标识");
                    row.CreateCell(3).SetCellValue("类型");
                    row.CreateCell(4).SetCellValue("参数");
                    row.CreateCell(5).SetCellValue("字段");
                    row.CreateCell(6).SetCellValue("重测次数");
                    row.CreateCell(7).SetCellValue("失败停止");
                    row.CreateCell(8).SetCellValue("范围");
                    var orders = (tabItem2.Content as TestListView).viewModel.Orders;
                    foreach (var order in orders)
                    {
                        row = sheet.CreateRow(order.index);
                        NpoiHelper.WriteCell(row, 0, order.index, cellStyle);
                        NpoiHelper.WriteCell(row, 1, order.name, cellStyle);
                        List<string> names = new List<string>();
                        if (order.deviceNames.Contains(null))
                        {
                            foreach (var name in order.deviceNames)
                            {
                                //如果是函数模块，将仪器名存为null
                                names.Add(name == null ? "null" : name );
                            }
                        }
                        else
                        {
                            names =  order.deviceNames;
                        }
                        //写入表格
                        NpoiHelper.WriteCell(row, 2, string.Join("\r\n", names), cellStyle);
                        NpoiHelper.WriteCell(row, 3, string.Join("\r\n", order.orderTemps), cellStyle);
                        NpoiHelper.WriteCell(row, 4, string.Join("\r\n", order.orderParameters), cellStyle);
                        NpoiHelper.WriteCell(row, 5, string.Join("\r\n", order.orderMeses), cellStyle);
                        NpoiHelper.WriteCell(row, 6, order.testTimes, cellStyle);
                        NpoiHelper.WriteCell(row, 7, order.ngStop == true ? "true" : "false", cellStyle);
                        NpoiHelper.WriteCell(row, 8, string.Join("\r\n", order.orderRanges), cellStyle);
                    }
                    //设置宽度
                    NpoiHelper.SetAutoWidth(sheet);
                }
                //写入内存
                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    workbooks.Add(tabItem.Header.ToString()+".xlsx", ms.ToArray());
                }
                //NpoiHelper.SaveExcel(workbook, dirctoryPath + "\\" + tabItem.Header.ToString() + ".xlsx");
            }
            //保存为压缩包
            new ZipHelper().CompressDirectory(path, workbooks,6);
            HandyControl.Controls.MessageBox.Success("保存成功");
        }

        private void StationTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}
